﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Xml;
using System.IO;
using Srvtools;

namespace EEPNetServer
{
    public partial class frmLoginMan : Form
    {
        private bool bHasSaved = true;

        public frmLoginMan()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
           
            try
            {
                SaveDomain();
                SrvGL.SaveConfig(chkAllowPerLogin.Checked, checkBoxLoginInSameIP.Checked);
                SrvGL.ResetAllowLoginInOtherPC();
                SrvGL.ResetAllowLoginInSameIP();
                ServerConfig.SaveUserTableConfig(checkBoxUserTable.Checked
                    , textBoxTable.Text, textBoxUserID.Text, textBoxUserName.Text, textBoxPassword.Text);
                SavePasswordPolicy();
            }
            catch(Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            bHasSaved = true;

            this.Close();
        }

        private void SavePasswordPolicy()
        { 
            string s = SystemFile.LoginFile;
            XmlDocument xml = new XmlDocument();
            XmlNode node = null;
            if (File.Exists(s))
            {
                xml.Load(s);
                node = xml.SelectSingleNode("InfolightAllowUserToPerLogin");
            }
            if (node == null)
            {
                node = xml.AppendChild(xml.CreateElement("InfolightAllowUserToPerLogin"));
            }
            XmlNode nodePolicy = node.SelectSingleNode("PasswordPolicy");
            if (nodePolicy == null)
            {
                nodePolicy = node.AppendChild(xml.CreateElement("PasswordPolicy"));
            }
            nodePolicy.RemoveAll();
            XmlAttribute att = xml.CreateAttribute("MinSize");
            ServerConfig.PassWordMinSize = Convert.ToInt32(textBoxPasswordMinSize.Text);
            att.Value = ServerConfig.PassWordMinSize.ToString();
            nodePolicy.Attributes.Append(att);
            att = xml.CreateAttribute("MaxSize");
            ServerConfig.PasswordMaxSize = Convert.ToInt32(textBoxPasswordMaxSize.Text);
            att.Value = ServerConfig.PasswordMaxSize.ToString();
            nodePolicy.Attributes.Append(att);
            att = xml.CreateAttribute("CharNum");
            ServerConfig.PasswordCharNum = checkBoxPasswordCharNum.Checked;
            att.Value = checkBoxPasswordCharNum.Checked.ToString();
            nodePolicy.Attributes.Append(att);
            xml.Save(s);
        }

        private void SaveDomain()
        {
            string s = SystemFile.DomainFile;
            if (File.Exists(s))
            {
                XmlDocument DomainXml = new XmlDocument();
                try
                {
                    DomainXml.Load(s);
                    XmlNode xn = DomainXml.SelectSingleNode("Infolight/Domain");
                    xn.Attributes["Path"].Value = tbDomain.Text;
                    xn.Attributes["User"].Value = tbAdministrator.Text;
                    xn.Attributes["Password"].Value = ServerConfig.Encrypt(tbAdministrator.Text, tbPassword.Text);
                    ServerConfig.DomainPath = tbDomain.Text;
                    ServerConfig.DomainUser = tbAdministrator.Text;
                    ServerConfig.DomainPassword = tbPassword.Text;
                    DomainXml.Save(s);
                }
                catch
                {
                    File.Delete(s);
                    SaveDomain();
                }
            }
            else
            {
                XmlTextWriter xw = new XmlTextWriter(s, Encoding.Unicode);
                xw.WriteStartElement("Infolight");
                xw.WriteStartElement("Domain");
                xw.WriteStartAttribute("Path");
                xw.WriteEndAttribute();
                xw.WriteStartAttribute("User");
                xw.WriteEndAttribute();
                xw.WriteStartAttribute("Password");
                xw.WriteEndAttribute();
                xw.WriteEndElement();
                xw.WriteEndElement();
                xw.Close();
                SaveDomain();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmLoginMan_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!bHasSaved)
            {
                if (MessageBox.Show("Setting has been changed. Are you sure to save them?", "Confirmation", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    btnOK_Click(null, null);
                }
            }
        }

        private void chkAllowPerLogin_CheckedChanged(object sender, EventArgs e)
        {
            bHasSaved = false;
        }

        private void frmLoginMan_Load(object sender, EventArgs e)
        {
            chkAllowPerLogin.Checked = SrvGL.AllowLoginInOtherPC;
            checkBoxLoginInSameIP.Checked = SrvGL.AllowLoginInSameIP;
            tbDomain.Text = ServerConfig.DomainPath;
            tbAdministrator.Text = ServerConfig.DomainUser;
            tbPassword.Text = ServerConfig.DomainPassword;
            checkBoxUserTable.Checked = ServerConfig.UserDefination;
            groupBoxUserTable.Enabled = checkBoxUserTable.Checked;
            textBoxTable.Text = ServerConfig.UserTable;
            textBoxUserID.Text = ServerConfig.UserID;
            textBoxUserName.Text = ServerConfig.UserName;
            textBoxPassword.Text = ServerConfig.Password;
            textBoxPasswordMinSize.Text = ServerConfig.PassWordMinSize.ToString();
            textBoxPasswordMaxSize.Text = ServerConfig.PasswordMaxSize.ToString();
            checkBoxPasswordCharNum.Checked = ServerConfig.PasswordCharNum;
            bHasSaved = true;
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            ADClass.ADPath = "LDAP://" + tbDomain.Text;
            ADClass.ADUser = tbAdministrator.Text;
            ADClass.ADPassword = tbPassword.Text;
            bool blsuc = ADClass.TestDirecoryOjbect();
            if (blsuc)
            {
                MessageBox.Show("Success to Connect to Domain:" + tbDomain.Text, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Fail to Connect to Domain:" + tbDomain.Text, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void checkBoxUserTable_CheckedChanged(object sender, EventArgs e)
        {
            groupBoxUserTable.Enabled = checkBoxUserTable.Checked;
        }
    }
}